import { auth } from './auth'

const BASE_URL = 'http://localhost:8080'

const request = (url, options = {}) => {
  return new Promise((resolve, reject) => {
    const fullUrl = `${BASE_URL}${url}`;
    console.log('完整请求URL:', fullUrl);
    console.log('请求参数:', options);

    // 添加token到header
    const token = auth.getToken()
    const header = {
      ...options.header,
    }
    
    if (token) {
      header.Authorization = `Bearer ${token}`
    }

    // 如果是上传文件
    if (options.filePath) {
      wx.uploadFile({
        url: fullUrl,
        filePath: options.filePath,
        name: options.name || 'file',
        header,
        success: (res) => {
          if (res.statusCode === 200) {
            const data = JSON.parse(res.data)
            if (data.code === 0) {
              resolve(data.data)
            } else {
              reject(new Error(data.message || '上传失败'))
            }
          } else {
            reject(new Error(`HTTP错误: ${res.statusCode}`))
          }
        },
        fail: (error) => {
          console.error(`上传失败: ${url}`, error)
          reject(error)
        }
      })
    } else {
      // 普通请求
      wx.request({
        url: fullUrl,
        ...options,
        header,
        timeout: 10000, // 10秒超时
        success: async (res) => {
          console.log(`接口返回: ${url}`, res)
          
          if (res.statusCode === 401) {
            // token过期，尝试重新登录
            try {
              const { code } = await wx.login()
              const loginRes = await authService.login(code)
              auth.setToken(loginRes.token)
              // 重试原请求
              const retryRes = await request(url, options)
              resolve(retryRes)
            } catch (error) {
              auth.clear()
              wx.redirectTo({ url: '/pages/login/login' })
              reject(error)
            }
          } else if (res.statusCode === 200) {
            if (res.data.code === 0) {
              resolve(res.data.data)
            } else {
              reject(new Error(res.data.message || '请求失败'))
            }
          } else {
            reject(new Error(`HTTP错误: ${res.statusCode}`))
          }
        },
        fail: (error) => {
          console.error(`请求失败: ${url}`, error)
          if (error.errMsg.includes('timeout')) {
            wx.showToast({
              title: '网络请求超时',
              icon: 'none'
            })
          }
          reject(error)
        }
      })
    }
  })
}

export default {
  get: (url, data) => request(url, { method: 'GET', data }),
  post: (url, data) => request(url, { method: 'POST', data }),
  put: (url, data) => request(url, { method: 'PUT', data }),
  delete: (url, data) => request(url, { method: 'DELETE', data })
} 